package com.itheima.tlias.tliasweb.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

@RestController
public class SessionController {

    public static class User implements Serializable {
    }

    @GetMapping("s1")
    public String createSession(HttpServletRequest request){
        // 登陆成功之后，把生成session，把用户id和用户名写入到session
        // 背后，服务器会把jsessionid放入cookie中输出给浏览器
        HttpSession session = request.getSession();// 如果初次访问，服务端没有对应的session就会创建一个新的session
        session.setAttribute("username", "zhangsan");
        session.setAttribute("age", "18");
        session.setAttribute("user", new User());//存储对象，需要让对象实现Serializable接口
        return "success";
    }

    @GetMapping("s2")
    public String getSession(HttpServletRequest request){
        // 浏览器下次请求的时候，会自动上传当前域下的cookie, 也就是jsessionid
        // 背后，服务器会根据jsessionid查找到session信息
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        String age = (String)session.getAttribute("age");
        return username + ":" + age;
    }
}
